package com.smscenter.server.core.ems;


import com.smscenter.server.core.IQuery;
import com.zeus.base.smscenter.common.constant.EmsConstants;
import com.zeus.base.smscenter.common.constant.SmsConstants;
import com.zeus.base.smscenter.common.security.MD5;
import com.zeus.base.smscenter.common.util.StringUtils;
import com.zeus.base.smscenter.common.util.WebUtils;
import com.zeus.base.smscenter.common.util.XMLParser;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


import java.util.HashMap;
import java.util.Map;

/**
 * Created by ShanFei on 2016-05-27.
 */
public class EmsQuery implements IQuery {
	
	public static void main(String[] args) throws Exception {
		//易信通：fyrjgstc  82557339    MD5.generate("82557339",false).toUpperCase()
		Map map = new HashMap();
		map.put("tenant", "fyrjgstc");
		map.put("password", "82557339");
		map.put("enterpriseID", EmsConstants.ENTERPRISEID);
		map.put("data", "{}");
		EmsQuery e = new EmsQuery();
		String s = e.queryBalance(map);
		System.out.println(s);
	}
	
    @Override
    public String queryBalance(Map<String, Object> params) throws Exception {
        String tenant = params.get("tenant")==null ? "":params.get("tenant").toString();
        String password = params.get("password")==null ? "":params.get("password").toString();
        String enterpriseID = params.get("enterpriseID")==null ? EmsConstants.ENTERPRISEID:params.get("enterpriseID").toString();
        if (StringUtils.isEmpty(enterpriseID)){
            throw  new Exception("参数:企业ID系统错误:error:企业ID不能为空");
        }
        if (StringUtils.isEmpty(tenant)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(password)){//MD5加密小写
            throw  new Exception("参数:租户密码系统错误:error:租户密码不能为空");
        }
        String returnMsg = "";
        try {
            Map<String,String> requestMap=new HashMap<String, String>();
            requestMap.put("enterpriseID",enterpriseID);
            requestMap.put("loginName",tenant);
            requestMap.put("password", MD5.generate(password,false));
            returnMsg = WebUtils.doPost(EmsConstants.EMS_QUERYBALANCE_URL,WebUtils.buildAllQuery(requestMap, SmsConstants.CHARSET_UTF8), SmsConstants.CHARSET_GBK, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }
        StringBuffer returnJson = new StringBuffer().append("{");
        String emsError = "";
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "Response");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
                String result = parser.getString(root,"Result");
                if (!result.equals("0")){
                    emsError = result;
                    throw  new Exception(emsError);
                }
                String balance = parser.getString(root,"Balance");
                if (i==0){
                    returnJson.append("\"accountName\"").append(":\"\",");
                    returnJson.append("\"inBalance\"").append(":\"\",");
                    returnJson.append("\"creditBalance\"").append(":\"\",");
                    returnJson.append("\"balance\"").append(":\"").append(balance).append("\"");
                }
            }
        }catch(Exception e){
            if(StringUtils.isEmpty(emsError))
                throw new Exception("解析XML失败");
            else
                throw new Exception(EmsError.getErrorMess(Integer.parseInt(emsError)));
        }
        returnJson.append("}");
        return returnJson.toString();
    }
    
    
    @Override
    public String queryBalanceV2(Map<String, Object> params) throws Exception {
        String loginName = params.get("loginName")==null ? "":params.get("loginName").toString();
        String password = params.get("loginPassword")==null ? "":params.get("loginPassword").toString();
        String enterpriseID = params.get("enterpriseID")==null ? EmsConstants.ENTERPRISEID:params.get("enterpriseID").toString();
        if (StringUtils.isEmpty(enterpriseID)){
            throw  new Exception("参数:企业ID系统错误:error:企业ID不能为空");
        }
        if (StringUtils.isEmpty(loginName)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(password)){//MD5加密小写
            throw  new Exception("参数:租户密码系统错误:error:租户密码不能为空");
        }
        String returnMsg = "";
        try {
            Map<String,String> requestMap=new HashMap<String, String>();
            requestMap.put("enterpriseID",enterpriseID);
            requestMap.put("loginName",loginName);
            requestMap.put("password", password);
            returnMsg = WebUtils.doPost(EmsConstants.EMS_QUERYBALANCE_URL,WebUtils.buildAllQuery(requestMap, SmsConstants.CHARSET_UTF8), SmsConstants.CHARSET_GBK, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }
        StringBuffer returnJson = new StringBuffer().append("{");
        String emsError = "";
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "Response");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
                String result = parser.getString(root,"Result");
                if (!result.equals("0")){
                    emsError = result;
                    throw  new Exception(emsError);
                }
                String balance = parser.getString(root,"Balance");
                String money = "0";
                if(!StringUtils.isEmpty(balance) && params.get("unitPrice") != null){
                	money = String.format("%.2f",Double.parseDouble((String) params.get("unitPrice")) * Double.parseDouble(balance));
                }
//                    returnJson.append("\"accountName\"").append(":\"\",");
//                    returnJson.append("\"inBalance\"").append(":\"\",");
//                    returnJson.append("\"creditBalance\"").append(":\"\",");
//                    returnJson.append("\"balance\"").append(":\"").append(balance).append("\"");
            	returnJson.append("\"money\"").append(":\"").append(money).append("\",");
                returnJson.append("\"balance\"").append(":\"").append(balance).append("\"");
            }
        }catch(Exception e){
            if(StringUtils.isEmpty(emsError))
                throw new Exception("解析XML失败");
            else
                throw new Exception(EmsError.getErrorMess(Integer.parseInt(emsError)));
        }
        returnJson.append("}");
        return returnJson.toString();
    }
    

    @Override
    public String queryCollect(Map<String, Object> params) throws Exception {
       return null;
    }

	@Override
	public String querySendRecordInfo(Map<String, Object> params)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
